package thomas.ssl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

@SpringBootApplication
public class App {
	
	private static final String TRUSTSTORE_PROPERTY = "javax.net.ssl.trustStore";
	
	private static final String DEFAULT_TRUSTSTORE_LOCATION = "classpath:META-INF/ssl/truststore.jks";
	
	private static  Logger LOG = LoggerFactory.getLogger(App.class);
	
	/**
	 * The trustStore is used to  communicate with another application (whose keystore should have same certificate) by SSL
	 * @param args
	 */
	public static void main(String[] args){
		if(System.getProperties().containsKey(TRUSTSTORE_PROPERTY)){
			LOG.info("Truststore set via -D{}={}", TRUSTSTORE_PROPERTY, System.getProperty(TRUSTSTORE_PROPERTY));
		}else{
			PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
			Resource resource = resolver.getResource(DEFAULT_TRUSTSTORE_LOCATION);
			if(resource.exists()){
				File file;
				try {
					file = resource.getFile();
					System.setProperty(TRUSTSTORE_PROPERTY, file.getAbsolutePath());
				} catch (IOException e) {
					// if the resource can't be access as a file
					try(InputStream source = resource.getInputStream()){
						Path truststore = Files.createTempFile("truststore", ".jks");
						truststore.toFile().deleteOnExit();
						LOG.info("Overridding -D{}={}", TRUSTSTORE_PROPERTY, truststore.toAbsolutePath());
						System.setProperty(TRUSTSTORE_PROPERTY, truststore.toAbsolutePath().toString());
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}

			}
		}
		
		new SpringApplicationBuilder(App.class).run(args);
	}
}
